package com.zmn.plat.admin.controller.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.KvDTO;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.business.interfaces.servcategory.ShowCategoryAssociationBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.category.BaseCategoryAttributeEnum;
import com.zmn.plat.model.entity.category.BaseCategoryQuery;
import com.zmn.plat.model.entity.channel.Channel;
import com.zmn.plat.model.entity.extension.serv.category.group.ExtensionServCategoryGroupQuery;
import com.zmn.plat.model.entity.product.*;
import com.zmn.plat.model.entity.product.tariff.ProductTariffQuery;
import com.zmn.plat.model.entity.servcategory.ServAssCategoryQuery;
import com.zmn.plat.model.entity.servcategory.ServCategory;
import com.zmn.plat.model.entity.servcategory.ShowCategoryAssociationVO;
import com.zmn.plat.model.vo.extension.serv.category.group.ExtensionServCategoryGroupVO;
import com.zmn.plat.model.vo.product.ServProductBackVO;
import com.zmn.plat.model.vo.product.ServProductVO;
import com.zmn.plat.model.vo.product.tariff.ProductTariffVO;
import com.zmn.plat.model.vo.servcategory.BaseCategoryAttributeVO;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.product.ServProductRelationService;
import com.zmn.plat.services.interfaces.product.ServTariffProductRelationService;
import com.zmn.plat.services.interfaces.product.tariff.ProductTariffService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 描述: 产品管理查询控制
 *
 * @author tanghongjun
 * @since: 2018/11/5 22:06
 */
@Controller
@RequestMapping("/product/")
public class ServProductListController extends ServProductBaseController {

    private Logger logger = LoggerFactory.getLogger(ServProductListController.class);
    @Resource
    ServProductRelationService servProductRelationService;
    @Resource
    ServTariffProductRelationService servTariffProductRelationService;
    @Resource
    ShowCategoryAssociationBService showCategoryAssociationBService;
    @Resource
    protected ChannelService channelService;
    @Resource
    protected ProductTariffService productTariffService;

    /**
     * 描述: 区域列表
     *
     * @param query 查询实体
     * @return ModelAndView
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "list")
    public ModelAndView list(@ModelAttribute ServProductQuery query) {

        ModelAndView mav = new ModelAndView("product/list");
        query.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
        try {
            ServCategory querySC = new ServCategory();
            List<ServCategory> servCategories = servCategoryService.listByQuery(querySC);

            List<FicoCategory> ficoCategoryList = ficoCategoryService.listAll();

            List<BaseCategory> baseCategories = Collections.emptyList();
            if (NumberUtil.isPositiveInteger(query.getServCategId())) {
                baseCategories = servAssCategoryService.findCategoryOneByServIdAndShowType(query.getServCategId(), query.getShowType());
            }

            List<ServAssCategoryVO> baseCategoryTwoList = Collections.emptyList();
            if (NumberUtil.isPositiveInteger(query.getCategOneId())) {
                ServAssCategoryQuery queryBQ = new ServAssCategoryQuery();
                queryBQ.setServCategId(query.getServCategId());
                queryBQ.setCategOneId(query.getCategOneId());
                queryBQ.setShowType(query.getShowType());
                baseCategoryTwoList = servAssCategoryService.listByQuery(queryBQ);
            }

            int count = servProductService.countByQueryForBackProduct(query);
            query.setTotalCount(count);
            List<ServProductBackVO> servProducts = servProductService.listPageByQueryForBackProduct(query);
            List<ServProductVO> items = new ArrayList<>();

            ServProductVO servProductView;
            ServProductBackVO servProduct;

            BaseCategoryQuery queryB = new BaseCategoryQuery();
            List<BaseCategory> baseCategorieall = baseCategoryService.listByQuery(queryB);

            for (int i = 0; i < servProducts.size(); i++) {
                servProduct = servProducts.get(i);
                servProductView = new ServProductVO();
                BeanUtils.copyProperties(servProduct, servProductView);

                servProductView.setFicoCtegName(servProductBService.findFicoCategNameById(ficoCategoryList, servProduct.getFicoCtegId()));
                servProductView.setServCategName(
                        servProductBService.findServCategNameById(servCategories, servProduct.getServCategId(), servProduct.getShowType()));
                servProductView.setCategOneName(servProductBService.findBaseCategNameById(baseCategorieall, servProduct.getCategOneId()));
                servProductView.setCategName(servProductBService.findBaseCategNameById(baseCategorieall, servProduct.getCategId()));
                if (StringUtils.isNotEmpty(servProduct.getBizType())) {
                    servProductView.setBizTypeStr(servProductService.translateBizTypeStrByBizType(servProduct.getBizType()));
                }
                items.add(servProductView);
            }

            // 前台台产品数据
            ServProductQuery servProductQuery = new ServProductQuery();
            servProductQuery.setShowType(ProductConsts.EC_PRODUCT_TYPE);
            List<ServProduct> showProducts = servProductService.listByQuery(servProductQuery);

            List<Channel> channelList = channelService.listTwoLevelChannel(null, null);

            mav.addObject("channelList", channelList);
            mav.addObject("ficoCategoryList", ficoCategoryList);
            mav.addObject("items", items);
            mav.addObject("vo", query);
            mav.addObject("servCategories", servCategories);
            mav.addObject("baseCategories", baseCategories);
            mav.addObject("baseCategoryTwoList", baseCategoryTwoList);
            mav.addObject("priceTypes", GlobalDict.getPriceTypeList());
            mav.addObject("productTypes", GlobalDict.getProductTypeList());
            mav.addObject("status", GlobalDict.getMasterState());
            mav.addObject("showProducts", showProducts);
            mav.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mav;
    }

    /**
     * 描述: 产品详情
     *
     * @param productId 产品ID
     * @return ModelAndView 产品详情页面
     */
    @RequestMapping("detail")
    public ModelAndView detail(@RequestParam(value = "productId", defaultValue = "0") Integer productId) {

        ServProduct servProduct = productId > 0 ? servProductService.findByKey(productId) : new ServProduct();
        if (productId.equals(ProductDict.ZERO)) {
            servProduct.setProductId(productId);
        }

        ModelAndView mav = new ModelAndView("product/detail");

        mav.addObject("servProduct", servProduct);
        mav.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());
        return mav;
    }

    /**
     * 描述: 批量设置产品排放量
     *
     * @param ids 产品ID串
     * @return ModelAndView 批量设置产品排放量页面
     */
    @RequestMapping("updateTotalEmissionsView")
    public ModelAndView updateTotalEmissionsView(@RequestParam(value = "ids", defaultValue = "") String ids) {
        ModelAndView mav = new ModelAndView("product/updateTotalEmissionsView");

        if (StringUtil.isBlank(ids)) {
            return mav;
        }
        KvDTO kvDTO = new KvDTO();
        kvDTO.setKey(ids);

        mav.addObject("kvDTO", kvDTO);
        return mav;
    }

    /**
     * 描述: 产品添加，修改页面 跳转方法
     *
     * @param productId 产品id
     * @return modelAndView
     * @author tanghongjun
     * @since 2018/10/16 11:10
     */
    @RequestMapping(value = "addEditView")
    public ModelAndView addEditView(@RequestParam(value = "productId", defaultValue = "0") Integer productId,
                                    @RequestParam(value = "productType", defaultValue = "0") Integer productType,
                                    @RequestParam(value = "channelId", defaultValue = "0") Integer channelId) {

        ServProduct product;
        if (productId > ProductDict.ZERO) {
            product = servProductService.findByKey(productId);
        } else {
            product = new ServProduct();
            product.setProductType(productType);
        }

        ModelAndView modelAndView = new ModelAndView("product/detail");

        if (Objects.nonNull(product.getProductType()) && Objects.equals(product.getProductType(), 2)) {
            List<Channel> channelList = channelService.listTwoLevelChannel(null, null);
            modelAndView.addObject("channelList", channelList);
        }

        ServProductVO servProductVO = new ServProductVO();
        List<ServProduct> showProducts = new ArrayList<>();
        Integer relationId = 0;
        // 查出关联关系并赋值
        ServProductRelationQuery query = new ServProductRelationQuery();
        query.setProductId(productId);
        List<ServProductRelation> relations = servProductRelationService.listByQuery(query);
        if (!CollectionUtils.isEmpty(relations)) {
            relationId = relations.get(0).getShowProductId();
        }
        // 修改产品需要查询相应的前台产品
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        servProductQuery.setServCategId(product.getServCategId());
        // 查询分类关联关系显示前台产品
        List<Integer> categOneIds = new ArrayList<>();
        List<Integer> categIds = new ArrayList<>();
        List<ShowCategoryAssociationVO> showCategoryAssociationVOS = productId > ProductDict.ZERO ?
                showCategoryAssociationBService.listByCategoryId(product.getServCategId(), product.getCategOneId(), product.getCategId()) : Collections.emptyList();
        if (!CollectionUtils.isEmpty(showCategoryAssociationVOS)) {
            showCategoryAssociationVOS.forEach(e -> {
                categOneIds.add(e.getShowCategOneId());
                categIds.add(e.getShowCategId());
            });
            servProductQuery.setCategOneIds(categOneIds);
            servProductQuery.setCategIds(categIds);
            servProductQuery.setDefaultType(GlobalConsts.NO);
            showProducts = servProductService.listByQuery(servProductQuery);
            servProductQuery.setDefaultType(null);
        }
        BeanUtils.copyProperties(product, servProductVO);
        if (null != relationId && !relationId.equals(0)) {
            servProductVO.setShowProductId(relationId);
        }

        // 查询计价器产品
        List<ServProduct> tariffProducts = new ArrayList<>();
        relationId = 0;
        servProductQuery.setShowType(ProductConsts.ET_PRODUCT_TYPE);
        if (!CollectionUtils.isEmpty(showCategoryAssociationVOS)) {
            tariffProducts = servProductService.listByQuery(servProductQuery);
        }

        // 查出关联关系并赋值
        ServTariffProductRelationQuery tariffProductRelationQueryuery = new ServTariffProductRelationQuery();
        tariffProductRelationQueryuery.setProductId(productId);
        List<ServTariffProductRelation> tariffRelations = servTariffProductRelationService.listByQuery(tariffProductRelationQueryuery);
        if (!CollectionUtils.isEmpty(tariffRelations)) {
            relationId = tariffRelations.get(0).getTariffProductId();
        }
        if (null != relationId && !relationId.equals(0)) {
            servProductVO.setTariffProductId(relationId);
        }

        ServCategory querySC = new ServCategory();
        querySC.setStatus(GlobalConsts.YES);
        List<ServCategory> servCategories = servCategoryService.listByQuery(querySC);
        // 是修改的情况下，需要将禁用的服务分类添加到集合中用于显示
        if (product.getProductId() != null) {
            ServCategory category = servCategoryService.findByKey(product.getServCategId());
            if (!category.getStatus().equals(GlobalConsts.YES)) {
                servCategories.add(category);
            }
        }

        List<KvDTO<Integer, String>> baseCategories = Collections.emptyList();
        List<ServAssCategoryVO> categoryVOList = Collections.emptyList();
        List<BaseCategoryAttributeVO> attrList = Collections.emptyList();
        List<FicoCategory> ficoCategoryList = ficoCategoryService.listAll();

        if (product.getProductId() != null) {
            ServAssCategoryQuery queryBQ = new ServAssCategoryQuery();
            queryBQ.setServCategId(product.getServCategId());
            queryBQ.setCategOneStatus(GlobalConsts.YES);
            queryBQ.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
            baseCategories = servAssCategoryService.listCateOneByQuery(queryBQ);

            BaseCategoryQuery baseCategoryQueryOne = new BaseCategoryQuery();
            baseCategoryQueryOne.setCategId(product.getCategOneId());
            List<BaseCategory> baseList = baseCategoryService.listByQuery(baseCategoryQueryOne);

            BaseCategory baseCategoryOne = CollectionUtils.isEmpty(baseList) ? null : baseList.get(0);
            if (baseCategoryOne != null && !baseCategoryOne.getStatus().equals(GlobalConsts.YES)) {
                baseCategories.add(new KvDTO<>(baseCategoryOne.getCategId(), baseCategoryOne.getName()));
            }

            ServAssCategoryQuery servAssCategoryQuery = new ServAssCategoryQuery();
            servAssCategoryQuery.setCategOneId(product.getCategOneId());
            servAssCategoryQuery.setServCategId(product.getServCategId());
            servAssCategoryQuery.setCategTwoStatus(GlobalConsts.YES);
            servAssCategoryQuery.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
            categoryVOList = servAssCategoryService.listByQuery(servAssCategoryQuery);

            BaseCategoryQuery baseCategoryQueryTwo = new BaseCategoryQuery();
            baseCategoryQueryTwo.setCategId(product.getCategId());
            List<BaseCategory> baseCategoryTwoList = baseCategoryService.listByQuery(baseCategoryQueryTwo);
            BaseCategory baseCategoryTwo = CollectionUtils.isEmpty(baseCategoryTwoList) ? null : baseCategoryTwoList.get(0);
            if (baseCategoryTwo != null && !baseCategoryTwo.getStatus().equals(GlobalConsts.YES)) {
                ServAssCategoryVO vo = new ServAssCategoryVO();
                vo.setCategId(baseCategoryTwo.getCategId());
                vo.setCategName(baseCategoryTwo.getName());
                categoryVOList.add(vo);
            }
            if (NumberUtil.isPositiveInteger(product.getCategOneId()) && NumberUtil.isPositiveInteger(product.getCategId())) {
                attrList = servProductBService.findAttrById(product.getCategOneId(), product.getCategId(), product.getChannelId());
            }
        }

        ServSubsidiaryGroupQuery subQuery = new ServSubsidiaryGroupQuery();
        subQuery.setType(ProductConsts.SERV_SUB_TYPE_HITCH);
        subQuery.setStatus(GlobalConsts.YES);
        List<ServSubsidiaryGroup> faults = servSubsidiaryGroupService.listByQuery(subQuery);

        subQuery.setType(ProductConsts.SERV_SUB_TYPE_GUARANTEE);
        List<ServSubsidiaryGroup> warrantys = servSubsidiaryGroupService.listByQuery(subQuery);

        List<ExtensionServCategoryGroupVO> extensionCategorys = new ArrayList<>();
        if (product.getServCategId() != null) {
            ExtensionServCategoryGroupQuery extensionServCategoryGroupQuery = new ExtensionServCategoryGroupQuery();
            extensionServCategoryGroupQuery.setExtensionServCategId(product.getServCategId());
            extensionCategorys = extensionServCategoryGroupService.listByQuery(extensionServCategoryGroupQuery);
        }

        modelAndView.addObject("priceStatement", product.getPriceStatement());
        modelAndView.addObject("attrList", attrList);
        modelAndView.addObject("ficoCategoryList", ficoCategoryList);
        modelAndView.addObject("servProductVO", servProductVO);
        modelAndView.addObject("servCategories", servCategories);
        modelAndView.addObject("baseCategories", baseCategories);
        modelAndView.addObject("categoryVOList", categoryVOList);
        modelAndView.addObject("faults", faults);
        modelAndView.addObject("warrantys", warrantys);
        List<String> unitList = listAllUnitName();
        modelAndView.addObject("unitList", unitList);
        modelAndView.addObject("flag", 1);
        modelAndView.addObject("showProducts", showProducts);
        modelAndView.addObject("tariffProducts", tariffProducts);
        modelAndView.addObject("extensionCategorys", extensionCategorys);
        modelAndView.addObject("channelId", channelId);
        modelAndView.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());

        return modelAndView;
    }

    /**
     * 描述: 产品添加，修改页面 跳转方法
     *
     * @param productId 产品id
     * @return modelAndView
     * @author tanghongjun
     * @since 2018/10/16 11:10
     */
    @RequestMapping(value = "editDescView")
    public ModelAndView editDescView(@RequestParam(value = "productId", defaultValue = "0") Integer productId) {

        ServProduct product = productId > ProductDict.ZERO ? servProductService.findByKey(productId) : new ServProduct();
        ModelAndView modelAndView = new ModelAndView("product/productdesc");
        ServProductVO servProductVO = new ServProductVO();

        BeanUtils.copyProperties(product, servProductVO);

        modelAndView.addObject("servProductVO", servProductVO);
        modelAndView.addObject("flag", 2);
        return modelAndView;
    }

    @RequestMapping(value = "channelDetail")
    @ResponseBody
    public ResponseDTO channelDetail(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam(value = "channelId", defaultValue = "0") Integer channelId) {
        if (channelId == null || channelId == ProductDict.ZERO) {
            return ResponseDTO.fail("channelId不能为空");
        }

        Channel channel = channelService.findByKey(channelId);

        return ResponseDTO.success(channel, "操作成功");

    }

    /**
     * 描述：分类联动（服务分类查询一级产品分类）原有方法不做变动
     *
     * @param parentId 服务分类
     * @updater wangjie 2019-10-15 方法提取,使其支持showType分类过滤
     */
    @RequestMapping(value = "listChilds")
    public void listChilds(HttpServletResponse response, @RequestParam(value = "parentId", defaultValue = "1") int parentId) {
        super.loadListChilds(response, parentId, null);
    }

    /**
     * 描述: 分类联动（服务分类查询一级产品分类）新增方法增强
     *
     * @param response 响应
     * @param parentId 服务分类id
     * @param showType 前台产品,后台产品标识 1后端 2 前端
     * @author wangjie
     * @since 2019/10/15
     **/
    @RequestMapping(value = "listChildsAndShowType")
    public void listChilds(HttpServletResponse response, @RequestParam(value = "parentId", defaultValue = "1") Integer parentId,
                           @RequestParam(value = "showType") Integer showType) {
        super.loadListChilds(response, parentId, showType);
    }

    /**
     * 分类联动(根据一级产品分类ID和服务类型ID查询二级产品分类) 原有方法不做变动
     *
     * @param categOneId  一级产品分类ID
     * @param servCategId 服务分类ID
     * @updater wangjie 2019-10-15 方法提取,使其支持showType分类过滤
     */
    @RequestMapping(value = "listCateChilds")
    public void listCateChilds(HttpServletResponse response, @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                               @RequestParam(value = "servCategId", defaultValue = "1") int servCategId) {
        super.loadListCateChilds(response, categOneId, servCategId, null);
    }

    /**
     * 分类联动(根据一级产品分类ID和服务类型ID查询二级产品分类)
     *
     * @param categOneId  一级产品分类ID
     * @param servCategId 服务分类ID
     */
    @RequestMapping(value = "listCateChildsAndShowType")
    public void listCateChildsAndShowType(HttpServletResponse response,
                                          @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                                          @RequestParam(value = "servCategId", defaultValue = "1") int servCategId, @RequestParam(value = "showType") Integer showType) {
        super.loadListCateChilds(response, categOneId, servCategId, showType);
    }

    /**
     * 分类联动(根据一级产品分类ID和服务类型ID查询二级产品分类)，返回数据支持下拉多选
     *
     * @param categOneId  一级产品分类ID
     * @param servCategId 服务分类ID
     */
    @RequestMapping(value = "listCateChildsJson")
    public void listCateChildsJson(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                                   @RequestParam(value = "servCategId", defaultValue = "1") int servCategId) {
        if (servCategId == ProductDict.ZERO || categOneId == ProductDict.ZERO) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }
        ServAssCategoryQuery query = new ServAssCategoryQuery();
        query.setCategOneId(categOneId);
        query.setServCategId(servCategId);
        query.setCategTwoStatus(GlobalConsts.YES);
        query.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
        List<ServAssCategoryVO> items = servAssCategoryService.listByQuery(query);

        List<VtDTO> list = Lists.newArrayList();
        if (items != null && !items.isEmpty()) {
            for (ServAssCategoryVO item : items) {
                VtDTO vtDTO = new VtDTO(item.getCategId(), item.getCategName());
                list.add(vtDTO);
            }
        }
        ResponseUtil.outWrite(response, JSON.toJSONString(list));
    }

    /**
     * 属性联动（一级产品分类和二级产品分类查询属性列表）
     *
     * @param categId,   二级产品分类ID
     * @param categOneId 一级产品分类ID
     */
    @RequestMapping(value = "listAttrChilds")
    public void listAttrChilds(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(value = "categId", defaultValue = "1") int categId,
                               @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                               @RequestParam(value = "channelId", defaultValue = "0") Integer channelId) {

        if (categId == ProductDict.ZERO || categOneId == ProductDict.ZERO) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseCategoryAttributeVO> items = servProductBService.findAttrById(categOneId, categId, channelId);

        ResponseUtil.outWrite(response, JSONObject.toJSONString(items));
    }

    /**
     * 属性值联动（根据属性ID查询属性值列表）
     *
     * @param parentId 属性名ID
     */
    @RequestMapping(value = "listEnumChilds")
    public void listEnumChilds(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(value = "parentId", defaultValue = "1") int parentId) {
        if (parentId == ProductDict.ZERO) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseCategoryAttributeEnum> items = baseCategoryAttributeEnumService.listAttributeId(parentId);

        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";
        BaseCategoryAttributeEnum item;
        String name;
        for (int i = 0; i < items.size(); i++) {
            item = items.get(i);
            name = item.getEnumValue();
            sb.append(String.format(jsonFormat, items.get(i).getEnumId(), name, (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * 描述: 初始化产品列表
     *
     * @param categId     二级产品类型ID
     * @param categOneId  一级产品类型ID
     * @param servCategId 服务ID
     */
    @RequestMapping("listProduct")
    public void listProduct(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "servCategId", defaultValue = "1") int servCategId,
                            @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                            @RequestParam(value = "categId", defaultValue = "1") int categId) {
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setServCategId(servCategId);
        servProductQuery.setCategOneId(categOneId);
        servProductQuery.setCategId(categId);
        servProductQuery.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
        List<ServProduct> servProductList = servProductService.listByQuery(servProductQuery);

        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < servProductList.size(); i++) {
            ServProduct item = servProductList.get(i);
            sb.append(String.format(jsonFormat, item.getProductId(), item.getName(), (i == servProductList.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * 描述：联动服务分类联动前台产品
     *
     * @param servCategId 服务分类
     */
    @RequestMapping(value = "listShowProducts")
    public void listShowProducts(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "servCategId", defaultValue = "1") int servCategId,
                                 @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                                 @RequestParam(value = "categId", defaultValue = "1") int categId) {
        if (servCategId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }
        List<ServProduct> showProducts = new ArrayList<>();
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        servProductQuery.setServCategId(servCategId);
        // 查询分类关联关系显示前台产品
        List<Integer> categOneIds = new ArrayList<>();
        List<Integer> categIds = new ArrayList<>();
        List<ShowCategoryAssociationVO> showCategoryAssociationVOS =
                showCategoryAssociationBService.listByCategoryId(servCategId, categOneId, categId);
        if (!CollectionUtils.isEmpty(showCategoryAssociationVOS)) {
            showCategoryAssociationVOS.forEach(e -> {
                categOneIds.add(e.getShowCategOneId());
                categIds.add(e.getShowCategId());
            });
            servProductQuery.setCategOneIds(categOneIds);
            servProductQuery.setCategIds(categIds);
            servProductQuery.setDefaultType(GlobalConsts.NO);
            showProducts = servProductService.listByQuery(servProductQuery);
            servProductQuery.setDefaultType(null);
        }
        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < showProducts.size(); i++) {
            ServProduct item = showProducts.get(i);
            sb.append(String.format(jsonFormat, item.getProductId(),
                    item.getName() + "(" + (Objects.equals(item.getStatus(), GlobalConsts.YES) ? "上架" : "下架") + ")",
                    (i == showProducts.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * 描述：联动服务分类联动计价器产品
     *
     * @param servCategId 服务分类
     */
    @RequestMapping(value = "listTariffProducts")
    public void listTariffProducts(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "servCategId", defaultValue = "1") int servCategId,
                                   @RequestParam(value = "categOneId", defaultValue = "1") int categOneId,
                                   @RequestParam(value = "categId", defaultValue = "1") int categId) {
        if (servCategId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }
        List<ServProduct> showProducts = new ArrayList<>();
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setShowType(ProductConsts.ET_PRODUCT_TYPE);
        servProductQuery.setServCategId(servCategId);
        // 查询分类关联关系显示前台产品
        List<Integer> categOneIds = new ArrayList<>();
        List<Integer> categIds = new ArrayList<>();
        List<ShowCategoryAssociationVO> showCategoryAssociationVOS =
                showCategoryAssociationBService.listByCategoryId(servCategId, categOneId, categId);
        if (!CollectionUtils.isEmpty(showCategoryAssociationVOS)) {
            showCategoryAssociationVOS.forEach(e -> {
                categOneIds.add(e.getShowCategOneId());
                categIds.add(e.getShowCategId());
            });
            servProductQuery.setCategOneIds(categOneIds);
            servProductQuery.setCategIds(categIds);
            showProducts = servProductService.listByQuery(servProductQuery);
        }
        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < showProducts.size(); i++) {
            ServProduct item = showProducts.get(i);
            sb.append(String.format(jsonFormat, item.getProductId(),
                    item.getName() + "(" + (Objects.equals(item.getStatus(), GlobalConsts.YES) ? "上架" : "下架") + ")",
                    (i == showProducts.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * 描述: 根据条件导出产品Excel
     *
     * @param query 查询条件
     * @author wangjie
     * @since 11:43 2019/2/19
     **/
    @RequestMapping(value = "outputExcel")
    // @RequiresPermissions("/product/outputExcel.action")
    public void outputExcel(HttpServletResponse response, ServProductQuery query) {

        // 前端产品类型
        query.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
        Integer pageSize = getExportPageLimit(response);
        query.setPageSize(pageSize);
        ArrayList<List> lists = servProductBService.outputProductExcel(query);
        try {
            String name = "后台产品报表.xlsx";
            name = new String(name.getBytes(), "ISO8859-1");
            ExcelUtil.export(response, lists, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出报表出错" + e.getMessage(), e);
        }
    }

    /**
     * 描述: 产品价格表页面跳转
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author wangjie
     * @since 2019/8/27
     **/
    @RequestMapping(value = "price/listProductPrice")
    public ModelAndView listProductPrice(@ModelAttribute ProductTariffQuery query) {

        Integer productId = query.getProductId() == null ? 0 : query.getProductId();
        ModelAndView mv = new ModelAndView("product/pricetable/list");
        ServProduct servProduct = productId > 0 ? servProductService.findByKey(productId) : new ServProduct();
        List<ProductTariffVO> list = productTariffService.listPageByQuery(query);
        mv.addObject("servProductVO", servProduct);
        mv.addObject("flag", 5);
        mv.addObject("items", list);
        mv.addObject("vo", query);

        // List<ProductPriceTableVO> productPriceTable = super.initProductPriceTable(productId);
        //
        // mv.addObject("outSide", super.getProductPriceTableGroup(productPriceTable, ProductDict.WARRANTY_TYPE_OUT));
        // mv.addObject("inSide", super.getProductPriceTableGroup(productPriceTable, ProductDict.WARRANTY_TYPE_IN));
        return mv;
    }
}
